# -*- coding: utf-8 -*-

import os

from django.conf import settings
from django.core.management import BaseCommand

from common.log import logger
from common.management import BaseDataBaseManager, BaseDataMigrate


# ==============================================================================
# 数据库迁移实现示例
# ==============================================================================
class DefaultMigration(BaseDataBaseManager):
    """
    迁移操作默认示例
    """

    @classmethod
    def create_backup_path(cls):
        logger.info("starting create backup path")
        if not os.path.isdir(settings.DEFAULT_BACKUP_PATH):
            os.makedirs(settings.DEFAULT_BACKUP_PATH)
        logger.info("create backup path finish")

    @classmethod
    def backup_tables(cls, database, tables, path):
        logger.info(f"starting backup {database}")
        for table in tables:
            file_path = os.path.join(path, f"{table}.sql")
            command = (
                f"mysqldump -h {settings.DB_HOST} -P {settings.DB_PORT} "
                f"-u{settings.DB_USERNAME} -p{settings.DB_PASSWORD} {database} {table} >{file_path}"
            )
            os.system(command)
            logger.info(f"backup {database} {table} finish")
        logger.info(f"backup {database} finish")

    def migrate_tables(self):
        DefaultDataMigrate.migrate()


class DefaultDataMigrate(BaseDataMigrate):
    """
    实际数据迁移操作之一
    """

    def migrate(self, table):
        logger.info(f"starting migrate {table}")
        # 写入实际数据迁移逻辑
        logger.info(f"migrate {table} finish")


class Command(BaseCommand):
    def handle(self, *args, **options):
        # 创建备份目录
        DefaultMigration.create_backup_path()

        # 备份mysql表
        DefaultMigration.backup_tables()

        # 执行所有数据迁移操作
        DefaultMigration.migrate_tables()
